<?php

namespace App\Http\Controllers\Component;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class OssController extends Controller
{
    /**
     * 返回OSS的签名验证
     * @return JSON 签名信息
     */
    public function sign(Request $request)
    {
        //初始化一下必要的请求数据
        $id = 'LTAI4G6wiH3sr3HdA1mcMW6e';   //AccessKeyId
        $key = 'msV8p0WVUmiGDKZHa0d1RqeSzrycJv';  //AccessKeySecret
        $host = 'http://novel-read.oss-cn-shenzhen.aliyuncs.com';  //OSS库地址
        $cdn_host = "http://novel-read.oss-cn-shenzhen.aliyuncs.com"; //真实的访问地址
        $dir = 'noDeal_Original/';  //上传目录设置
        $callbackUrl = url('upload/callback');  //上传回调的地址

        //上传回调的参数,callbackUrl地址,callbackBody回调接收的参数,callbackBodyType通过POST调用的回调函数,所以要设置这个头
        $callback_param = array(
            'callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType =${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded"
        );
        $callback_string = json_encode($callback_param);  //转换成json格式
        $base64_callback_body = base64_encode($callback_string); //要返回的回调函数参数信息

        //设置过期时间
        $now = time();

        $expire = 60 * 60 * 2; //设置该policy超时时间是 2小时. 即这个policy过了这个有效时间，将不能访问，这里可以根据自己的token过期时间来设置
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);  //进行时间格式的转换


        //处理上传限制条件
        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition; //设定文件大小
        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;  //必须以设定的目录开头,防止上传错误
        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);  //要返回的上传限制参数

        //签名信息
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));  //要返回的签名信息

        //设置返回信息
        $response = array(
            'accessid' => $id,  //accessid
            'host' => $host,    //上传地址
            'cdn_host' => $cdn_host,    //真实的访问地址
            'policy' => $base64_policy,  //上传文件限制
            'signature' => $signature,   //签名信息
            'expire' => $end,    //失效时间
            'callback' => $base64_callback_body,  //上传回调参数
            'dir' => $dir     //上传的目录
        );
        return response()->json([
            'code' => 0,
            'msg' => 'success',
            'data' => $response
        ]);
    }

    //格式化时间,格式为2020-07-07T23:48:43Z
    public function gmt_iso8601($time)
    {
        $dtStr = date("c", $time);
        $pos = strpos($dtStr, '+');
        $expiration = substr($dtStr, 0, $pos);
        return $expiration . "Z";
    }
}
